<template>
  <div id="params">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告提示区域 -->
      <el-alert
        title="注意:只允许为第三级分类设置相关参数!"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="el_option">
        <el-col>
          <span>选择商品分类: </span>
          <el-cascader
            expand-trigger="hover"
            :props="cascader_props"
            v-model="selected_keys"
            :options="cate_list"
            @change="parent_cate_changed"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 标签页区域 -->
      <el-tabs v-model="active_name" @tab-click="handle_tab_click">
        <!-- 添加动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="is_btn_disabled"
            @click="add_dialog_visible = true"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table class="el_tabs_table" :data="many_table_data" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染 tag 标签 -->
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handle_close(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入的文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作" prop="attr_name">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="show_edit_dialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="del_params(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="is_btn_disabled"
            @click="add_dialog_visible = true"
            >添加属性</el-button
          >
          <!-- 静态属性表格 -->
          <el-table class="el_tabs_table" :data="only_table_data" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染 tag 标签 -->
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handle_close(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入的文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作" prop="attr_name">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="show_edit_dialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="del_params(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加动态 参数/属性 对话框 -->
    <el-dialog
      :title="'添加' + title_data"
      :visible.sync="add_dialog_visible"
      width="50%"
      @close="add_dialog_closed"
    >
      <el-form
        :model="add_form"
        :rules="add_form_rules"
        ref="add_form_ref"
        label-width="100px"
      >
        <el-form-item :label="title_data" prop="attr_name">
          <el-input v-model="add_form.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="add_dialog_visible = false">取 消</el-button>
        <el-button type="primary" @click="add_params">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑参数对话框 -->
    <el-dialog
      :title="'编辑' + title_data"
      :visible.sync="edit_dialog_visible"
      width="50%"
      @close="edit_dialog_closed"
    >
      <el-form
        :model="edit_form"
        :rules="edit_form_rules"
        ref="edit_form_ref"
        label-width="100px"
      >
        <el-form-item :label="title_data" prop="attr_name">
          <el-input v-model="edit_form.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="edit_dialog_visible = false">取 消</el-button>
        <el-button type="primary" @click="edit_params">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 商品分类列表
      cate_list: [],
      // 指定级联选择器的配置对象
      cascader_props: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        checkStrictly: true,
      },
      // 父级分类的数据列表
      parents_list: [],
      // 选中的父级分类 ID 数组
      selected_keys: [],
      // 被激活的标签名称
      active_name: "many",
      // 动态参数从的数据
      many_table_data: [],
      // 静态属性的数据
      only_table_data: [],
      // 控制添加 参数/属性 对话框的显示与隐藏
      add_dialog_visible: false,
      // 表单提交数据对象
      add_form: {
        attr_name: "",
      },
      // 添加表单验证对象
      add_form_rules: {
        attr_name: [
          { required: true, message: "请输入参数名称", tigger: "blur" },
        ],
      },
      // 控制编辑对话框的显示与隐藏
      edit_dialog_visible: false,
      // 修改表单数据对象
      edit_form: {
        attr_name: "",
      },
      // 编辑表单验证对象
      edit_form_rules: {
        attr_name: [
          { required: true, message: "请输入参数名称", tigger: "blur" },
        ],
      },
      // 控制文本框与按钮的切换
      inputVisible: false,
      // 文本框中输入的内容
      inputValue: "",
    };
  },
  created() {
    this.get_params_list();
  },
  methods: {
    // 获取所有商品分类数据
    async get_params_list() {
      let { data: res } = await this.axios.get("categories");
      if (res.meta.status !== 200) {
        return this.message.error("获取商品分类失败");
      }
      this.cate_list = res.data;
    },
    // 监听级联选择器发生改变时
    parent_cate_changed() {
      this.get_parents_list();
    },
    // tab 页签点击事件的处理函数
    async handle_tab_click() {
      this.get_parents_list();
    },
    // 获取父级节点
    async get_parents_list() {
      if (this.selected_keys.length !== 3) {
        this.selected_keys = [];
        this.many_table_data = [];
        this.only_table_data = [];
        return;
      }
      // 证明选中的时三级分类

      // 根据所选的id,和当前所处的面板,湖区对应的参数
      let { data: res } = await this.axios.get(
        `categories/${this.cate_id}/attributes`,
        {
          params: { sel: this.active_name },
        }
      );
      if (res.meta.status !== 200) {
        return this.message.error("获取参数失败");
      }
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        // 控制文本框的显示与隐藏
        item.inputVisible = false;
        // 文本框的输入值
        item.inputValue = "";
      });
      if (this.active_name === "many") {
        this.many_table_data = res.data;
      } else {
        this.only_table_data = res.data;
      }
    },
    // 监听添加对话框关闭,清空表单
    add_dialog_closed() {
      this.$refs.add_form_ref.resetFields();
    },
    // 点击按钮,添加参数
    add_params() {
      this.$refs.add_form_ref.validate(async (valid) => {
        if (!valid) return;
        let { data: res } = await this.axios.post(
          `categories/${this.cate_id}/attributes`,
          {
            attr_name: this.add_form.attr_name,
            attr_sel: this.active_name,
          }
        );
        if (res.meta.status !== 201) {
          return this.message.error("添加参数失败");
        }
        this.message.success("添加参数成功");
        this.add_dialog_visible = false;
        this.get_parents_list();
      });
    },
    // 点击按钮,展示编辑对话框
    async show_edit_dialog(attr_id) {
      let { data: res } = await this.axios.get(
        `categories/${this.cate_id}/attributes/${attr_id}`,
        {
          params: {
            attr_sel: this.active_name,
          },
        }
      );
      if (res.meta.status !== 200) {
        return this.message.error("修改元素失败");
      }
      this.edit_form = res.data;
      this.edit_dialog_visible = true;
    },
    // 监听修改对话框关闭,清空表单
    edit_dialog_closed() {
      this.$refs.edit_form_ref.resetFields();
    },
    // 点击按钮,修改参数
    edit_params(attr_id) {
      this.$refs.edit_form_ref.validate(async (valid) => {
        if (!valid) return;
        let { data: res } = await this.axios.put(
          `categories/${this.cate_id}/attributes/${this.edit_form.attr_id}`,
          {
            attr_name: this.edit_form.attr_name,
            attr_sel: this.active_name,
          }
        );
        if (res.meta.status !== 200) {
          return this.message.error("编辑失败");
        }
        this.message.success("编辑成功");
        this.edit_dialog_visible = false;
        this.get_parents_list();
      });
    },
    // 点击按钮,删除参数
    async del_params(attr_id) {
      let confirm_result = await this.confirm(
        "此操作将永远删除该参数,是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      // 点击确定,返回 confirm
      // 点击取消,返回 cancel
      if (confirm_result !== "confirm") {
        return this.message.info("已取消删除");
      }
      let { data: res } = await this.axios.delete(
        `categories/${this.cate_id}/attributes/${attr_id}`
      );
      if (res.meta.status !== 200) {
        return this.message.error("删除失败");
      }
      this.message.success("删除成功");
      this.get_parents_list();
    },
    // 文本框失去焦点,或按下了 Enter 都会触发
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      // 如果没有return ,则证明输入内容,需要做后续处理
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = "";
      row.inputVisible = false;
      // 发起请求,保存此操作
      this.save_attr_vals(row)
    },
    // 将对 attr_vals 的操作保存到数据库
    async save_attr_vals(row) {
      let { data: res } = await this.axios.put(
        `categories/${this.cate_id}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" "),
        }
      );
      if (res.meta.status !== 200) {
        return this.message.error("修改参数项失败");
      }
      this.message.success("修改参数项成功");
    },
    // 点击按钮,展示输入框
    showInput(row) {
      row.inputVisible = true;
      // 让文本框自动获得焦点
      // $nextTick 方法,就是当页面上元素被重新渲染之后才会指定回调中的代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 删除对应的参数可选项
    handle_close(i, row) {
      row.attr_vals.splice(i, 1);
      this.save_attr_vals(row)
    },
  },
  computed: {
    // 如果按钮需要被禁用,返回true , 否则返回false
    is_btn_disabled() {
      if (this.selected_keys.length !== 3) {
        return true;
      }
      return false;
    },
    // 当前选中的三级类别id
    cate_id() {
      if (this.selected_keys.length === 3) {
        return this.selected_keys[2];
      }
      return null;
    },
    // 添加动态 参数/属性 的title
    title_data() {
      if (this.active_name === "many") {
        return "动态参数";
      }
      return "静态属性";
    },
  },
};
</script>
<style lang="less" scoped>
.el_option {
  margin: 15px 0;
}
.el_tabs_table {
  margin-top: 15px;
}
.input-new-tag {
  width: 120px;
}
</style>